//! 组织服务
//! 提供组织成员管理相关的业务逻辑

use crate::client::EntityClient;
use crate::models::party::*;
use crate::models::party_relationship::*;
use crate::models::view_entities::*;
use crate::models::*;
use crate::services::{QueryBuilder, PagedResult, utils};
use crate::{Result, PartyModError};
use std::collections::HashMap;
use chrono::{DateTime, Utc};

/// 组织服务
#[derive(Clone)]
pub struct OrganizationService {
    client: EntityClient,
}

/// 组织成员信息
#[derive(Debug, Clone)]
pub struct OrganizationMember {
    pub party_id: String,
    pub organization_id: String,
    pub role_type_id: String,
    pub from_date: DateTime<Utc>,
    pub thru_date: Option<DateTime<Utc>>,
    pub position_title: Option<String>,
    pub comments: Option<String>,
    // 个人信息
    pub first_name: Option<String>,
    pub last_name: Option<String>,
    pub email: Option<String>,
    pub phone: Option<String>,
    // 组织信息
    pub organization_name: Option<String>,
}

/// 组织层级结构
#[derive(Debug, Clone)]
pub struct OrganizationHierarchy {
    pub organization_id: String,
    pub organization_name: String,
    pub parent_organization_id: Option<String>,
    pub parent_organization_name: Option<String>,
    pub level: i32,
    pub children: Vec<OrganizationHierarchy>,
}

impl OrganizationService {
    /// 创建新的组织服务
    pub fn new(client: EntityClient) -> Self {
        Self { client }
    }

    /// 创建组织
    pub async fn create_organization(
        &mut self,
        organization_name: &str,
        description: Option<&str>,
        parent_organization_id: Option<&str>
    ) -> Result<String> {
        let party_id = utils::generate_party_id();
        
        // 创建PartyGroup
        let party_group = PartyGroup {
            party_id: party_id.clone(),
            group_name: Some(organization_name.to_string()),
            group_name_local: None,
            office_site_name: None,
            annual_revenue: None,
            num_employees: None,
            ticker_symbol: None,
            comments: description.map(|s| s.to_string()),
            logo_image_url: None,
        };
        
        // 创建Party
        let party = Party {
            party_id: party_id.clone(),
            party_type_id: "PARTY_GROUP".to_string(),
            external_id: None,
            preferred_currency_uom_id: None,
            description: Some(organization_name.to_string()),
            status_id: Some("PARTY_ENABLED".to_string()),
            created_date: Some(Utc::now()),
            created_by_user_login: None,
            last_modified_date: Some(Utc::now()),
            last_modified_by_user_login: None,
            data_source_id: None,
            is_unread: Some(false),
        };
        
        // 插入Party数据
        let party_data = party.to_data_row();
        self.client.insert_data("Party", party_data).await?;
        
        // 插入PartyGroup数据
        let group_data = party_group.to_data_row();
        self.client.insert_data("PartyGroup", group_data).await?;
        
        // 添加组织角色
        let org_role = PartyRole {
            party_id: party_id.clone(),
            role_type_id: "INTERNAL_ORGANIZATIO".to_string(), // OFBiz标准角色类型
        };
        let role_data = org_role.to_data_row();
        self.client.insert_data("PartyRole", role_data).await?;
        
        // 如果有父组织，创建组织关系
        if let Some(parent_id) = parent_organization_id {
            self.create_organization_relationship(&party_id, parent_id).await?;
        }
        
        Ok(party_id)
    }

    /// 创建组织关系（子组织关系）
    pub async fn create_organization_relationship(
        &mut self,
        child_org_id: &str,
        parent_org_id: &str
    ) -> Result<()> {
        let relationship = PartyRelationship {
            party_id_from: parent_org_id.to_string(),
            party_id_to: child_org_id.to_string(),
            role_type_id_from: "INTERNAL_ORGANIZATIO".to_string(),
            role_type_id_to: "INTERNAL_ORGANIZATIO".to_string(),
            from_date: Utc::now(),
            thru_date: None,
            status_id: Some("PARTY_RELATIONSHIP_ACTIVE".to_string()),
            relationship_name: Some("Parent-Child Organization".to_string()),
            security_group_id: None,
            priority_type_id: None,
            party_relationship_type_id: Some("GROUP_ROLLUP".to_string()),
            permissions_enum_id: None,
            position_title: None,
            comments: None,
        };
        
        let data = relationship.to_data_row();
        self.client.insert_data("PartyRelationship", data).await?;
        Ok(())
    }

    /// 添加组织成员
    pub async fn add_member(
        &mut self,
        organization_id: &str,
        member_party_id: &str,
        role_type_id: &str,
        position_title: Option<&str>,
        from_date: Option<DateTime<Utc>>
    ) -> Result<()> {
        let from_date = from_date.unwrap_or_else(Utc::now);
        
        // 确保成员有相应的角色
        let member_role = PartyRole {
            party_id: member_party_id.to_string(),
            role_type_id: role_type_id.to_string(),
        };
        
        let role_data = member_role.to_data_row();
        // 尝试插入角色（如果已存在会失败，但不影响后续操作）
        let _ = self.client.insert_data("PartyRole", role_data).await;
        
        // 创建组织成员关系
        let relationship = PartyRelationship {
            party_id_from: organization_id.to_string(),
            party_id_to: member_party_id.to_string(),
            role_type_id_from: "INTERNAL_ORGANIZATIO".to_string(),
            role_type_id_to: "INTERNAL_ORGANIZATIO".to_string(), // 使用现有的角色类型
            from_date,
            thru_date: None,
            status_id: Some("PARTY_ENABLED".to_string()), // 使用现有的状态
            relationship_name: Some("Organization Member".to_string()),
            security_group_id: None,
            priority_type_id: None,
            party_relationship_type_id: None, // 暂时设为None
            permissions_enum_id: None,
            position_title: position_title.map(|s| s.to_string()),
            comments: None,
        };
        
        let data = relationship.to_data_row();
        self.client.insert_data("PartyRelationship", data).await?;
        Ok(())
    }

    /// 移除组织成员（通过更新状态为PARTY_DISABLED）
    pub async fn remove_member(
        &mut self,
        organization_id: &str,
        member_party_id: &str,
        _role_type_id: &str
    ) -> Result<()> {
        // 查找要移除的关系
        let query = QueryBuilder::new()
            .eq("partyIdFrom", organization_id)
            .eq("partyIdTo", member_party_id)
            .eq("roleTypeIdFrom", "INTERNAL_ORGANIZATIO")
            .eq("roleTypeIdTo", "INTERNAL_ORGANIZATIO")
            .build();
        
        let response = self.client.query_data(
            "PartyRelationship",
            None,
            Some(query.conditions),
            query.order_by.first().cloned(),
            query.limit,
            query.offset
        ).await?;
        
        println!("Debug: Found {} relationships to remove", response.len());
        
        for row in response {
            let mut relationship = PartyRelationship::from_data_row(&row.fields)?;
            println!("Debug: Removing relationship from {} to {} with roles {} -> {}", 
                relationship.party_id_from, relationship.party_id_to, 
                relationship.role_type_id_from, relationship.role_type_id_to);
            
            // 设置关系为已终止
            relationship.thru_date = Some(Utc::now());
            relationship.status_id = Some("PARTY_DISABLED".to_string());
            
            let data = relationship.to_data_row();
            
            // 使用所有原始字段作为更新条件
            let update_conditions: Vec<crate::models::QueryCondition> = row.fields.iter().map(|(key, value)| {
                crate::models::QueryCondition {
                    field: key.clone(),
                    operator: "=".to_string(),
                    value: value.clone(),
                    logic: "AND".to_string(),
                }
            }).collect();
            
            println!("Debug: Update conditions count: {}", update_conditions.len());
            let update_result = self.client.update_data("PartyRelationship", data, update_conditions).await;
            println!("Debug: Update result: {:?}", update_result);
            update_result?;
        }
        
        Ok(())
    }

    /// 获取组织的所有成员
    pub async fn get_organization_members(&mut self, organization_id: &str) -> Result<Vec<OrganizationMember>> {
        let query = QueryBuilder::new()
            .eq("partyIdFrom", organization_id)
            .eq("roleTypeIdFrom", "INTERNAL_ORGANIZATIO")
            .build();
        
        let response = self.client.query_data(
            "PartyRelationship",
            None,
            Some(query.conditions),
            query.order_by.first().cloned(),
            query.limit,
            query.offset
        ).await?;
        
        let mut members = Vec::new();
        for row in response {
            let relationship = PartyRelationship::from_data_row(&row.fields)?;
            
            // 过滤掉已终止的关系
            if let Some(thru_date) = relationship.thru_date {
                if thru_date <= Utc::now() {
                    continue;
                }
            }
            
            // 过滤掉状态为PARTY_DISABLED的关系
            if let Some(ref status) = relationship.status_id {
                if status == "PARTY_DISABLED" {
                    continue;
                }
            }
            
            let member = OrganizationMember {
                party_id: relationship.party_id_to,
                organization_id: relationship.party_id_from,
                role_type_id: relationship.role_type_id_to,
                from_date: relationship.from_date,
                thru_date: relationship.thru_date,
                position_title: relationship.position_title,
                comments: relationship.comments,
                first_name: None, // 需要额外查询Person表
                last_name: None, // 需要额外查询Person表
                email: None, // 需要额外查询联系方式
                phone: None, // 需要额外查询联系方式
                organization_name: None, // 需要额外查询PartyGroup表
            };
            
            members.push(member);
        }
        
        Ok(members)
    }

    /// 获取活跃的组织成员
    pub async fn get_active_organization_members(&mut self, organization_id: &str) -> Result<Vec<OrganizationMember>> {
        let now = Utc::now().format("%Y-%m-%d %H:%M:%S").to_string();
        
        let query = QueryBuilder::new()
            .eq("partyIdFrom", organization_id)
            .eq("roleTypeIdFrom", "INTERNAL_ORGANIZATIO")
            .lt("fromDate", &now)
            .build();
        
        let mut conditions = query.conditions;
        // 添加条件：thruDate为空或大于当前时间
        conditions.push(crate::models::QueryCondition {
            field: "thruDate".to_string(),
            operator: ">".to_string(),
            value: Utc::now().to_rfc3339(),
            logic: "AND".to_string(),
        });
        
        let response = self.client.query_data(
            "PartyRelationship",
            None,
            Some(conditions),
            query.order_by.first().cloned(),
            query.limit,
            query.offset
        ).await?;
        
        let mut members = Vec::new();
        for row in response {
            let relationship = PartyRelationship::from_data_row(&row.fields)?;
            
            // 检查关系是否仍然活跃
            if let Some(thru_date) = relationship.thru_date {
                if thru_date <= Utc::now() {
                    continue;
                }
            }
            
            let member = OrganizationMember {
                party_id: relationship.party_id_to,
                organization_id: relationship.party_id_from,
                role_type_id: relationship.role_type_id_to,
                from_date: relationship.from_date,
                thru_date: relationship.thru_date,
                position_title: relationship.position_title,
                comments: relationship.comments,
                first_name: None,
                last_name: None,
                email: None,
                phone: None,
                organization_name: None,
            };
            
            members.push(member);
        }
        
        Ok(members)
    }

    /// 根据角色获取组织成员
    pub async fn get_members_by_role(
        &mut self,
        organization_id: &str,
        role_type_id: &str
    ) -> Result<Vec<OrganizationMember>> {
        let query = QueryBuilder::new()
            .eq("partyIdFrom", organization_id)
            .eq("roleTypeIdFrom", "INTERNAL_ORGANIZATIO")
            .eq("roleTypeIdTo", role_type_id)
            .build();
        
        let response = self.client.query_data(
            "PartyRelationship",
            None,
            Some(query.conditions),
            query.order_by.first().cloned(),
            query.limit,
            query.offset
        ).await?;
        
        let mut members = Vec::new();
        for row in response {
            let relationship = PartyRelationship::from_data_row(&row.fields)?;
            
            let member = OrganizationMember {
                party_id: relationship.party_id_to,
                organization_id: relationship.party_id_from,
                role_type_id: relationship.role_type_id_to,
                from_date: relationship.from_date,
                thru_date: relationship.thru_date,
                position_title: relationship.position_title,
                comments: relationship.comments,
                first_name: None,
                last_name: None,
                email: None,
                phone: None,
                organization_name: None,
            };
            
            members.push(member);
        }
        
        Ok(members)
    }

    /// 获取个人所属的组织
    pub async fn get_person_organizations(&mut self, party_id: &str) -> Result<Vec<OrganizationMember>> {
        let query = QueryBuilder::new()
            .eq("partyIdTo", party_id)
            .eq("roleTypeIdFrom", "INTERNAL_ORGANIZATIO")
            .build();
        
        let response = self.client.query_data(
            "PartyRelationship",
            None,
            Some(query.conditions),
            query.order_by.first().cloned(),
            query.limit,
            query.offset
        ).await?;
        
        let mut organizations = Vec::new();
        for row in response {
            let relationship = PartyRelationship::from_data_row(&row.fields)?;
            
            let org_member = OrganizationMember {
                party_id: relationship.party_id_to,
                organization_id: relationship.party_id_from,
                role_type_id: relationship.role_type_id_to,
                from_date: relationship.from_date,
                thru_date: relationship.thru_date,
                position_title: relationship.position_title,
                comments: relationship.comments,
                first_name: None,
                last_name: None,
                email: None,
                phone: None,
                organization_name: None,
            };
            
            organizations.push(org_member);
        }
        
        Ok(organizations)
    }

    /// 获取组织层级结构
    pub async fn get_organization_hierarchy(&mut self, root_organization_id: &str) -> Result<OrganizationHierarchy> {
        // 获取根组织信息
        let query = QueryBuilder::new()
            .eq("partyId", root_organization_id)
            .build();
        
        let response = self.client.query_data(
            "PartyAndGroup",
            None,
            Some(query.conditions),
            query.order_by.first().cloned(),
            query.limit,
            query.offset
        ).await?;
        
        if let Some(row) = response.first() {
            let party_and_group = PartyAndGroup::from_data_row(&row.fields)?;
            
            let mut hierarchy = OrganizationHierarchy {
                organization_id: party_and_group.party_id,
                organization_name: party_and_group.group_name.unwrap_or_default(),
                parent_organization_id: None,
                parent_organization_name: None,
                level: 0,
                children: Vec::new(),
            };
            
            // 递归获取子组织
            hierarchy.children = self.get_child_organizations(&hierarchy.organization_id, 1).await?;
            
            Ok(hierarchy)
        } else {
            Err(Box::new(PartyModError::InvalidData(format!("Organization not found: {}", root_organization_id))))
        }
    }

    /// 递归获取子组织
    fn get_child_organizations<'a>(&'a mut self, parent_id: &'a str, level: i32) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<Vec<OrganizationHierarchy>>> + Send + 'a>> {
        Box::pin(async move {
        let query = QueryBuilder::new()
            .eq("partyIdFrom", parent_id)
            .eq("roleTypeIdFrom", "INTERNAL_ORGANIZATIO")
            .eq("roleTypeIdTo", "INTERNAL_ORGANIZATIO")
            .eq("partyRelationshipTypeId", "GROUP_ROLLUP")
            .build();
        
        let response = self.client.query_data(
            "PartyRelationship",
            None,
            Some(query.conditions),
            query.order_by.first().cloned(),
            query.limit,
            query.offset
        ).await?;
        
        let mut children = Vec::new();
        for row in response {
            let relationship = PartyRelationship::from_data_row(&row.fields)?;
            
            let mut child = OrganizationHierarchy {
                organization_id: relationship.party_id_to,
                organization_name: "Unknown".to_string(), // 需要额外查询PartyGroup表
                parent_organization_id: Some(parent_id.to_string()),
                parent_organization_name: None,
                level,
                children: Vec::new(),
            };
            
            // 递归获取子组织的子组织
            if level < 10 { // 防止无限递归
                child.children = self.get_child_organizations(&child.organization_id, level + 1).await?;
            }
            
            children.push(child);
        }
        
        Ok(children)
        })
    }

    /// 更新成员职位
    pub async fn update_member_position(
        &mut self,
        organization_id: &str,
        member_party_id: &str,
        role_type_id: &str,
        new_position_title: &str
    ) -> Result<()> {
        let query = QueryBuilder::new()
            .eq("partyIdFrom", organization_id)
            .eq("partyIdTo", member_party_id)
            .eq("roleTypeIdTo", role_type_id)
            .build();
        
        let response = self.client.query_data(
            "PartyRelationship",
            None,
            Some(query.conditions),
            query.order_by.first().cloned(),
            query.limit,
            query.offset
        ).await?;
        
        for row in response {
            let mut relationship = PartyRelationship::from_data_row(&row.fields)?;
            relationship.position_title = Some(new_position_title.to_string());
            
            let data = relationship.to_data_row();
            let update_conditions = vec![
                crate::models::QueryCondition {
                    field: "partyIdFrom".to_string(),
                    operator: "=".to_string(),
                    value: relationship.party_id_from.clone(),
                    logic: "AND".to_string(),
                },
                crate::models::QueryCondition {
                    field: "partyIdTo".to_string(),
                    operator: "=".to_string(),
                    value: relationship.party_id_to.clone(),
                    logic: "AND".to_string(),
                },
                crate::models::QueryCondition {
                    field: "roleTypeIdFrom".to_string(),
                    operator: "=".to_string(),
                    value: relationship.role_type_id_from.clone(),
                    logic: "AND".to_string(),
                },
                crate::models::QueryCondition {
                    field: "roleTypeIdTo".to_string(),
                    operator: "=".to_string(),
                    value: relationship.role_type_id_to.clone(),
                    logic: "AND".to_string(),
                },
            ];
            
            self.client.update_data("PartyRelationship", data, update_conditions).await?;
        }
        
        Ok(())
    }
}